package com.changgou.search.controller;

import com.changgou.search.feign.SkuFeign;
import com.changgou.search.pojo.SkuInfo;
import entity.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.Map;

/**
 * 接收用户发送的请求 调用feign 获取搜索的结果 渲染html 返回给用户
 *
 * @author ljh
 * @version 1.0
 * @package com.changgou.seach.controller *
 * @Date 2019-12-1
 * @since 1.0
 */
@Controller
@RequestMapping("/search")
public class SkuController {

    @Autowired
    private SkuFeign skuFeign;

    @GetMapping("/list")
    public String search(@RequestParam(required = false) Map<String, String> searchMap, Model model) {
        //1.接收页面传递的参数
        //2.调用feign 获取搜索的结果集
        Map search = skuFeign.search(searchMap);

        //3.将结果集添加到model中
        model.addAttribute("result",search);


        //数据回显
        model.addAttribute("searchMap",searchMap);

        //获取URL 进行返回
        String url = url(searchMap);
        model.addAttribute("url",url);
        //4.返回页面 渲染(thymeleaf的语法来渲染)

        //接收了当前页码的值 调用feign之后 返回再进行封装到PAGE对象(有左边开始的页码,右边开始的页码)
        Page<SkuInfo> page = new Page<SkuInfo>(
                Long.valueOf(search.get("total").toString()),
                Integer.valueOf(search.get("pageNum").toString()),
                Integer.valueOf(search.get("pageSize").toString()));
        model.addAttribute("page",page);


        return "search";
    }

    private String url(Map<String, String> searchMap){

        // 1.点击发送过来的URL路径   /search/list
        // 2.第二个点击 拼接 /search/list?keyowrds=抗
        // 3.三次点击: 拼接 /search/list?keyowrds=抗&brand=adfalj
        String url = "/search/list";
        if(searchMap!=null) {
            url+="?";
            for (Map.Entry<String, String> stringStringEntry : searchMap.entrySet()) {
                //判断如果是分页的key pageNum 就不需要拼接 跳过

                String key = stringStringEntry.getKey();//keywords
                if(key.equals("pageNum")){
                    continue;
                }
                String value = stringStringEntry.getValue();//手机
                url +=key+"="+value+"&";
            }

            //去除&号
            url= url.substring(0,url.length()-1);
        }

        return url;
    }
}
